# -*- coding:utf-8 -*-

import pyautogui
import pyperclip
import time
import os
import StateParam

path = StateParam.musicpath
imgpath = "../img/music/"

def getFile(mstr):
    path = searchone(mstr)
    print(path)
    if (path == None):
        print("去下载")
        if (downMusic(mstr)):

            path = searchone(mstr)
            if (path != None):
                print(path)
                return path
            return None

    return path


def searchone(mstr):
    print("查询")
    filenames = os.listdir(path)
    for name in filenames:
        if (('-' + mstr) in name and 'mp3' in name):
            return path + name

    return None


def downMusic(mstr):
    dw = dingwei()
    if (dw == None):
        print("dw none")
        return
    # 左上角 1080  895 Y:  42
    x = dw.left - 5
    y = dw.top - 570
    print(x, y)
    searchinput(x, y)

    pyautogui.hotkey('ctrl', 'a')

    pyautogui.press('delete')

    # pyautogui.write('123')
    pyperclip.copy(mstr)
    # time.sleep(1)
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('enter')
    time.sleep(1)

    ntime = 10
    while ntime:
        print("waiting")
        ntime -= 1
        # 下载第一个
        print(x, y)
        if (getjxzhuanj(x, y) == None):
            print("down1111")
            pyautogui.moveTo(x + 520, y + 295, duration=0.5)
            pyautogui.click(x + 520, y + 295)
        else:
            print("down2222")
            pyautogui.moveTo(x + 526, y + 382, duration=0.5)
            pyautogui.click(x + 526, y + 382)

        d = getdown(x, y)
        if (d != None):
            print("找到下载按钮", d)
            xiazai(x, y)
            pass

        r = getHasdown(x, y)
        if (r != None):
            print("找到已经下载", r)
            nullclick(x, y)

            return True

        ding = getdowning(x, y)
        if (ding != None):
            print("找到正在下载", d)
            nullclick(x, y)
            # time.sleep(1)
            pass
    return False


# 895 Y:  42
def nullclick(x, y):
    pyautogui.click(x + 628, y + 87)


def xiazai(x, y):
    # 下载按钮
    pyautogui.click(x + 550, y + 521)


def searchinput(x, y):
    pyautogui.click(x + 286, y + 30)


def dingwei():
    r = pyautogui.locateOnScreen(r"img/music/dingwei.png")
    return r


def getHasdown(x, y):
    r = pyautogui.locateOnScreen(r"img/music/hasdown.png", region=(x, y, 1024, 645))
    return r


def getdown(x, y):
    r = pyautogui.locateOnScreen(r"img/music/downp.png", region=(x, y, 1024, 645))
    return r


def getdowning(x, y):
    r = pyautogui.locateOnScreen(r"img/music/downing.png", region=(x, y, 1024, 645))
    return r


def getjxzhuanj(x, y):
    r = pyautogui.locateOnScreen(r"img/music/jxzhuanj.png", region=(x, y, 1024, 645))
    if(r ==None):
        r1 = pyautogui.locateOnScreen(r"img/music/bfzj.png", region=(x, y, 1024, 645))
        if(r1 !=None):
            return r1
    return r


